package com.dacool.fragment;

import java.util.ArrayList;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.dacool.app.sale.R;
import com.dacool.config.Config;
import com.dacool.helper.DaCoolHelper;
import com.dacool.http.BaseRequest;
import com.dacool.http.BaseRequest.ResponseHandler;
import com.dacool.http.GetOrderListRequest;
import com.dacool.model.DCUser;
import com.dacool.model.DaCoolTransactionBill;
import com.dacool.util.ViewUtils;

public class BillListFragment extends BaseFragment implements OnClickListener {

	private ArrayList<DaCoolTransactionBill> billList0 = new ArrayList<DaCoolTransactionBill>();
	private ArrayList<DaCoolTransactionBill> billList1 = new ArrayList<DaCoolTransactionBill>();
	// private ArrayList<DaCoolTransactionBill> billList2 = new
	// ArrayList<DaCoolTransactionBill>();
	private ArrayList<DaCoolTransactionBill> displayList;
	private ArrayAdapter<DaCoolTransactionBill> mAdapter;

	private Button pendingBtn;
	private Button doneBtn;
	// private Button expiredBtn;
	private View tabIndicator1;
	private View tabIndicator2;
	// private View tabIndicator3;

	int selectedTab = 0;

	private ListView billListView;

	@Override
	protected int myLayoutID() {
		// TODO Auto-generated method stub
		return R.layout.frag_mybills;
	}

	// @Override
	// protected boolean showDefaultLeftButton() {
	// return true;
	// }

	@Override
	protected boolean showDefaultSecondLeftButton() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	protected View myView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
		pendingBtn = (Button) view.findViewById(R.id.pending);
		doneBtn = (Button) view.findViewById(R.id.done);
		// expiredBtn = (Button) view.findViewById(R.id.expired);
		billListView = (ListView) view.findViewById(R.id.orderList);
		tabIndicator1 = view.findViewById(R.id.tabindicator1);
		tabIndicator2 = view.findViewById(R.id.tabindicator2);
		// tabIndicator3 = view.findViewById(R.id.tabindicator3);
		pendingBtn.setOnClickListener(this);
		doneBtn.setOnClickListener(this);
		// expiredBtn.setOnClickListener(this);
		// ArrayList<DaCoolTransactionBill> list = DaCoolHelper.sharedInstance()
		// .getMyBills();
		displayList = new ArrayList<DaCoolTransactionBill>();
		// for (DaCoolTransactionBill bill : list) {
		// if (bill.status == 0)
		// billList0.add(bill);
		// else if (bill.status == 1)
		// billList1.add(bill);
		// else
		// billList2.add(bill);
		//
		// }
		// if (0 == selectedTab)
		// displayList = billList0;
		// else if (1 == selectedTab)
		// displayList = billList1;
		// else
		// displayList = billList2;
		mAdapter = new ArrayAdapter<DaCoolTransactionBill>(getActivity(), 0) {
			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return displayList.size();
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				DaCoolTransactionBill bill = displayList.get(position);
				if (convertView == null) {
					View view = LayoutInflater.from(getActivity()).inflate(
							R.layout.orderlistitem, null);
					ViewHolder holder = new ViewHolder();
					holder.imageView = (ImageView) view
							.findViewById(R.id.imageView);
					holder.titleView = (TextView) view
							.findViewById(R.id.titleLabel);
					holder.descriptionLabel = (TextView) view
							.findViewById(R.id.idlabel);
					holder.priceLabel = (TextView) view
							.findViewById(R.id.priceLabel);
					holder.track = view.findViewById(R.id.track);
					holder.container = view;
					holder.container.setOnClickListener(BillListFragment.this);
					holder.track.setOnClickListener(BillListFragment.this);
					convertView = view;
					convertView.setTag(holder);
				}
				ViewHolder holder = (ViewHolder) convertView.getTag();
				holder.titleView.setText(bill.dateString);
				holder.descriptionLabel.setText(String.format("订单号 %s",
						bill.billId));
				holder.index = position;
				holder.priceLabel.setText(String.format("总价 ¥ %s",
						bill.totalPrice));
				if (bill.iconUrl != null) {
					ViewUtils.bmUtils.display(holder.imageView, bill.iconUrl);
				} else
					holder.imageView.setImageResource(R.drawable.bannerimg);
				holder.track.setTag(Integer.valueOf(position));
				holder.track
						.setVisibility(bill.status == 0 || bill.status == 3 ? View.GONE
								: View.VISIBLE);
				return convertView;
			}

		};
		pendingBtn.setClickable(selectedTab != 0);
		doneBtn.setClickable(selectedTab != 1);
		// expiredBtn.setClickable(selectedTab != 2);
		tabIndicator1.setBackgroundColor(selectedTab == 0 ? 0xFF85c400
				: Color.TRANSPARENT);
		tabIndicator2.setBackgroundColor(selectedTab == 1 ? 0xFF85c400
				: Color.TRANSPARENT);
		// tabIndicator3.setBackgroundColor(selectedTab == 2 ? 0xFF85c400
		// : Color.TRANSPARENT);
		billListView.setAdapter(mAdapter);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		this.loadBills(selectedTab == 0 ? 0 : selectedTab == 1 ? 1 : 3);
	}

	private void loadBills(final int type) {
		this.showProgressDialog(null, false);

		new GetOrderListRequest().setMemberId(DCUser.sharedUser().getUserId())
				.setType(type).setHandler(new ResponseHandler() {

					/**
					 * 　　{ “orders": [ 
					 * {orderId:”3342”, "orderNo": "10070532", "imgUrl"
					 * :"/1/2/1.jpg",”price” :”100” },{
					 * orderId:”3342”, "orderNo":
					 *  "10070532", "imgUrl":"/1/2/1.jpg",”price” :”100” },　{
					 * orderId
					 * :”3342”, "orderNo": "10070532", "imgUrl":"/1/2/1.jpg"
					 * ,,”price” :”100” }  　　]} 
					 * 
					 */
					@Override
					public void handleResponse(BaseRequest request,
							int statusCode, String errorMsg, String response) {
						BillListFragment.this.dismissProgressDialog();
						if (statusCode != 200)
							return;
						try {
							JSONObject object = new JSONObject(response);
							JSONArray orders = object.getJSONArray("data");
							ArrayList<DaCoolTransactionBill> list = new ArrayList<DaCoolTransactionBill>();
							for (int i = 0; i < orders.length(); i++) {
								JSONObject obj = orders.getJSONObject(i);
								DaCoolTransactionBill bill = new DaCoolTransactionBill();
								bill.billId = obj.getLong("orderId");
								// bill.orderNo = obj.getString("orderNo");
								bill.iconUrl = obj.optString("thumbnail", null);
								Date date = new Date(
										obj.getLong("createtime") * 1000);
								// Log.d("test", "date " + date);
								bill.dateString = DateFormat.format(
										"yyyy-MM-dd, hh:mm:ss", date)
										.toString();
								bill.totalPrice = obj.getDouble("finalAmount");
								bill.status = type;
								list.add(bill);
							}
							if (type == 0)
								billList0 = list;
							if (type == 1)
								billList1 = list;
							// if (type == 3)
							// billList2 = list;
							displayList = list;
							ViewUtils.runInMainThread(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									mAdapter.notifyDataSetChanged();
								}
							});
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}).start();
	}

	@Override
	public void onClick(View v) {
		if (v.getTag() instanceof Integer) {
			DaCoolTransactionBill transactionBill = displayList
					.get(((Integer) v.getTag()).intValue());

			BillTrackInfoFragment fragment = new BillTrackInfoFragment();
			fragment.setBillId(transactionBill.billId);
			getContainerActivity().addFragment(fragment);

		} else if (v.getTag() instanceof ViewHolder) {
			ViewHolder holder = (ViewHolder) v.getTag();
			DaCoolTransactionBill bill = displayList.get(holder.index);
			OrderFragmentStep2 frag = new OrderFragmentStep2();
			frag.setBill(bill);
			getContainerActivity().addFragment(frag);
		} else {
			selectedTab = v == pendingBtn ? 0 : v == doneBtn ? 1 : selectedTab;

			if (0 == selectedTab)
				displayList = billList0;
			else if (1 == selectedTab)
				displayList = billList1;

			mAdapter.notifyDataSetChanged();
			pendingBtn.setClickable(selectedTab != 0);
			doneBtn.setClickable(selectedTab != 1);
//			expiredBtn.setClickable(selectedTab != 2);
			tabIndicator1.setBackgroundColor(selectedTab == 0 ? 0xFF85c400
					: Color.TRANSPARENT);
			tabIndicator2.setBackgroundColor(selectedTab == 1 ? 0xFF85c400
					: Color.TRANSPARENT);
//			tabIndicator3.setBackgroundColor(selectedTab == 2 ? 0xFF85c400
//					: Color.TRANSPARENT);
			this.loadBills(selectedTab);
		}
		super.onClick(v);

	}

	class ViewHolder {
		ImageView imageView;
		TextView titleView;
		TextView descriptionLabel;
		TextView priceLabel;
		View track;
		int index;
		View container;
	}

}
